package com.ljl.rest;

import com.baidu.aip.ocr.AipOcr;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
 * @author 刘家良
 * @date 2022/10/30 16:17
 * @description
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class FaceDetectController {

    private final AipOcr aipOcr = new AipOcr("25776151", "IOHfhchnRUBXnjRpfEbfCBgS", "RYp86CwVW9wZRPPM4gxZYlAhBeyC22Ax");

    private final String tempFilePath = "temp";

    /**
     * 上传
     * @param fileUpload 图片资源
     * @return 图映射的虚拟访问路径
     */
    @PostMapping("/upload")
    public ResponseEntity<Object> upload(@RequestParam("file") MultipartFile fileUpload) {
        //获取文件名
        String fileName = fileUpload.getOriginalFilename();
        //获取文件后缀名。也可以在这里添加判断语句，规定特定格式的图片才能上传，否则拒绝保存。
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String[] fileType = new String[]{"jpg", "bmp", "png"};
        List<String> list = Arrays.asList(fileType);
        if (!list.contains(suffixName.toLowerCase(Locale.ROOT))) {
            return new ResponseEntity<>("格式不正确", HttpStatus.BAD_REQUEST);
        }
        File tempPath = new File(tempFilePath);
        if (!tempPath.exists()) {
            boolean mkdir = tempPath.mkdir();
            if ((!mkdir)) {
                return new ResponseEntity<>("文件夹创建失败", HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        try {
            String filePath = tempFilePath + File.separator + UUID.randomUUID() + "." + suffixName;
            //将图片保存
            fileUpload.transferTo(new File(filePath).getAbsoluteFile());
            //是否检测多张车牌
            HashMap<String, String> options = new HashMap<>();
            options.put("multi_detect", "true");
            JSONObject res = aipOcr.plateLicense(filePath, options);
            JSONArray wordsResult = res.getJSONArray("words_result");
            for (int i = 0; i < wordsResult.length(); i++) {
                JSONObject jsonObject = wordsResult.getJSONObject(i);
                String color = jsonObject.getString("color");
                String number = jsonObject.getString("number");
                JSONArray arr = jsonObject.getJSONArray("probability");
                double probability = arr.getDouble(7);
                log.info("颜色[{}],号码[{}],平均可信度[{}]", color, number, probability);
            }
            return new ResponseEntity<>(HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseEntity<>("系统异常", HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
